from application import *
import json
from httpServer.reflectRun import *
import error


# 将字典转成字符串
def dict2str(d):
    s = ''
    for i in d:
        s = s + i + ': ' + d[i] + '\r\n'
    return s


class HttpResponse():

    def __init__(self):
        self.response_line = None
        self.response_head = dict()
        self.response_body = {}

    # 设置返回体
    def get_response_ok(self, result):
        self.response_line = error.ErrorCode.OK
        self.response_head['content-Type'] = 'application/json;charset=utf-8'
        self.response_body['returnCode'] = 200
        self.response_body['returnMsg'] = '操作成功'
        self.response_body['returnData'] = result
        return self.response_line + dict2str(self.response_head) + '\r\n' + json.dumps(self.response_body)

    # 设置返回体
    def get_response_error(self, e):
        self.response_line = error.ErrorCode.OK
        self.response_head['content-Type'] = 'application/json;charset=utf-8'
        self.response_body['returnCode'] = 500
        self.response_body['returnMsg'] = e
        self.response_body['returnData'] = '操作失败'
        return self.response_line + dict2str(self.response_head) + '\r\n' + json.dumps(self.response_body)


class HttpRequest():

    def __init__(self):
        self.method = None
        self.url = None
        self.protocol = None
        self.head_body = dict()
        self.path = None
        self.params = dict()

    # 处理请求头(POST /url HTTP/1.1)
    def handle_head_line(self, head):
        heads_params = head.split(' ')
        self.method = heads_params[0].upper()
        self.url = heads_params[1]
        self.protocol = heads_params[2]

    # 处理请求头主机信息（Host: 127.0.0.1:1111）
    def handle_head_body(self, head_body):
        for bean in head_body.split('\r\n'):
            key, val = bean.split(': ', 1)
            self.head_body[key] = val

    # 处理get 请求
    def handle_get(self):
        if self.url.find('?') != -1:  # get请求带有参数
            path, params = self.url.split('?', 1)
            self.url = path
            for bean in params.split('&'):
                key, val = bean.split('=', 1)
                self.params[key] = val
        # 反射执行函数
        return ReflectRun().run(self.url, self.params)

    # 处理post 请求
    def handle_post(self, post_body):
        if len(post_body) == 0:
            # 报错 提示post请求没有参数
            raise error.MyError(error.ErrorCode.METHOD_POST_BODY_NONE)
        else:
            self.params = json.loads(post_body)
        return ReflectRun().run(self.url, self.params)

    # 处理匹配request请求信息
    def handle_request(self, request_data):
        request = request_data.decode('utf-8')
        # 解析request
        line, body = request.split('\r\n', 1)
        head_body, request_body = body.split('\r\n\r\n', 1)  # 头部信息
        self.handle_head_line(line)
        self.handle_head_body(head_body)

        if self.url == '/':
            return
        elif self.url == '/favicon.ico':
            return

        if HTTP_GET == self.method:
            return self.handle_get()
        elif HTTP_POST == self.method:
            return self.handle_post(request_body)
        else:
            raise error.MyError(error.ErrorCode.METHOD_POST_BODY_NONE)
